package com.xbongbong.workflow.service.strategy.node.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.business.rule.RuleBusinessLogger;
import com.xbongbong.paas.config.enums.WorkflowTaskLogStatusEnum;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormSubDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.model.PaasFormSubDataEsModel;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.exception.WorkflowException;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.FormDataHelp;
import com.xbongbong.sys.help.PackageHelp;
import com.xbongbong.paas.pojo.workflow.WorkflowDataPojo;
import com.xbongbong.paas.pojo.workflow.WorkflowExplainPojo;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.paas.util.FormUtil;
import com.xbongbong.paas.util.WorkflowExplainUtil;
import com.xbongbong.paas.util.WorkflowNodeUtil;
import com.xbongbong.paas.util.WorkflowUtil;
import com.xbongbong.parent.util.ConditionUtil;
import com.xbongbong.pro.constant.BusinessConstant;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.domain.entity.UpdateDataValueEntity;
import com.xbongbong.pro.domain.entity.UpdateSubDataEntity;
import com.xbongbong.pro.enums.PackageTypeEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.BusinessRuleErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.workflow.WorkflowValueTypeEnum;
import com.xbongbong.pro.form.pojo.RuleTargetPojo;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.pro.log.pojo.dto.RuleBusinessLogDTO;
import com.xbongbong.pro.score.pojo.dto.DataScoreUpdateBatchDTO;
import com.xbongbong.pro.workflow.enums.WorkflowOperateEnum;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.model.AssembleModel;
import com.xbongbong.saas.model.BomBillModel;
import com.xbongbong.saas.model.ClueModel;
import com.xbongbong.saas.model.CommunicatePlanModel;
import com.xbongbong.saas.model.ContactModel;
import com.xbongbong.saas.model.ContractModel;
import com.xbongbong.saas.model.CostAdjustModel;
import com.xbongbong.saas.model.CustomerCommunicateModel;
import com.xbongbong.saas.model.CustomerModel;
import com.xbongbong.saas.model.IndexTypeModel;
import com.xbongbong.saas.model.InstockModel;
import com.xbongbong.saas.model.InventoryModel;
import com.xbongbong.saas.model.InvoiceModel;
import com.xbongbong.saas.model.MarketActivityModel;
import com.xbongbong.saas.model.OpportunityModel;
import com.xbongbong.saas.model.OutstockModel;
import com.xbongbong.saas.model.PaasFormDataModel;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.model.PayPlanModel;
import com.xbongbong.saas.model.PayPlanSheetModel;
import com.xbongbong.saas.model.PaymentModel;
import com.xbongbong.saas.model.PaymentSheetModel;
import com.xbongbong.saas.model.ProductModel;
import com.xbongbong.saas.model.ProductionOrderModel;
import com.xbongbong.saas.model.PurchaseInvoiceModel;
import com.xbongbong.saas.model.PurchaseModel;
import com.xbongbong.saas.model.QuotationModel;
import com.xbongbong.saas.model.RefundModel;
import com.xbongbong.saas.model.ReturnedPurchaseModel;
import com.xbongbong.saas.model.SupplierCommunicateModel;
import com.xbongbong.saas.model.SupplierContactModel;
import com.xbongbong.saas.model.SupplierModel;
import com.xbongbong.saas.model.TransferModel;
import com.xbongbong.saas.model.WarehouseModel;
import com.xbongbong.saas.model.WorkOrderModel;
import com.xbongbong.saas.service.ScoreCalculateService;
import com.xbongbong.util.DataTypeUtil;
import com.xbongbong.workflow.domain.entity.WorkflowBackupDataEntity;
import com.xbongbong.workflow.domain.entity.WorkflowNodeEntity;
import com.xbongbong.workflow.enums.WorkflowNodeTypeEnum;
import com.xbongbong.workflow.feign.WorkflowWorkOrderV2FeignClient;
import com.xbongbong.workflow.model.WorkflowBackupDataModel;
import com.xbongbong.workflow.model.WorkflowNodeModel;
import com.xbongbong.workflow.pojo.Data;
import com.xbongbong.workflow.pojo.FilterCondition;
import com.xbongbong.workflow.pojo.FlowData;
import com.xbongbong.workflow.pojo.FlowDatas;
import com.xbongbong.workflow.pojo.User;
import com.xbongbong.workflow.pojo.WorkflowFilterConditionPoJo;
import com.xbongbong.workflow.pojo.WorkflowOperationsPojo;
import com.xbongbong.workflow.pojo.WorkflowProcessResultPojo;
import com.xbongbong.workflow.pojo.WorkflowRulePojo;
import com.xbongbong.workflow.pojo.WorkflowTransferPOJO;
import com.xbongbong.workflow.pojo.nodes.ObtainMultiDataNode;
import com.xbongbong.workflow.pojo.nodes.ObtainSingleDataNode;
import com.xbongbong.workflow.pojo.nodes.UpdateRecordNode;
import com.xbongbong.workflow.pojo.workorderv2.dto.WorkflowUpdateDataDTO;
import com.xbongbong.workflow.service.field.WorkflowConditionFieldService;
import com.xbongbong.workflow.service.help.WorkflowDataNodeHelp;
import com.xbongbong.workflow.service.operator.impl.WorkflowOperatorMainServiceImpl;
import com.xbongbong.workflow.service.operator.impl.WorkflowOperatorMainSubFormServiceImpl;
import com.xbongbong.workflow.service.operator.impl.WorkflowOperatorSubFormMainServiceImpl;
import com.xbongbong.workflow.service.operator.impl.WorkflowOperatorSubFormServiceImpl;
import com.xbongbong.workflow.service.strategy.node.AbstractWorkflowNodeStrategy;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.support.WriteRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 更新记录节点
 * @author 魏荣杰
 *
 */
@Service("workflowNodeUpdateStrategy")
public class WorkflowNodeUpdateStrategy extends AbstractWorkflowNodeStrategy {

    private static final Logger LOGGER = LoggerFactory.getLogger(WorkflowNodeUpdateStrategy.class);
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;
    @Resource
    private WorkflowNodeModel workflowNodeModel;
    @Resource
    private WorkflowDataNodeHelp workflowDataNodeHelp;
    @Resource
    private WorkflowOperatorMainServiceImpl workflowOperatorMainService;
    @Resource
    private WorkflowOperatorSubFormMainServiceImpl workflowOperatorSubFormMainService;
    @Resource
    private WorkflowOperatorMainSubFormServiceImpl workflowOperatorMainSubFormService;
    @Resource
    private WorkflowOperatorSubFormServiceImpl workflowOperatorSubFormService;
    @Resource
    private Map<Integer, WorkflowConditionFieldService> workflowConditionFieldMap;
    @Resource
    private PaasFormSubDataEsModel paasFormSubDataEsModel;
    @Resource
    private PaasFormDataModel paasFormDataModel;
    @Resource
    private CustomerModel customerModel;
    @Resource
    private ContactModel contactModel;
    @Resource
    private CustomerCommunicateModel customerCommunicateModel;
    @Resource
    private CommunicatePlanModel communicatePlanModel;
    @Resource
    private OpportunityModel opportunityModel;
    @Resource
    private ContractModel contractModel;
    @Resource
    private RefundModel refundModel;
    @Resource
    private QuotationModel quotationModel;
    @Resource
    private SupplierModel supplierModel;
    @Resource
    private SupplierContactModel supplierContactModel;
    @Resource
    private SupplierCommunicateModel supplierCommunicateModel;
    @Resource
    private PurchaseModel purchaseModel;
    @Resource
    private ReturnedPurchaseModel returnedPurchaseModel;
    @Resource
    private BomBillModel bomBillModel;
    @Resource
    private ProductionOrderModel productionOrderModel;
    @Resource
    private AssembleModel assembleModel;
    @Resource
    private InstockModel instockModel;
    @Resource
    private OutstockModel outstockModel;
    @Resource
    private InventoryModel inventoryModel;
    @Resource
    private TransferModel transferModel;
    @Resource
    private WarehouseModel warehouseModel;
    @Resource
    private PaymentModel paymentModel;
    @Resource
    private PaymentSheetModel paymentSheetModel;
    @Resource
    private PayPlanModel payPlanModel;
    @Resource
    private PayPlanSheetModel payPlanSheetModel;
    @Resource
    private InvoiceModel invoiceModel;
    @Resource
    private PurchaseInvoiceModel purchaseInvoiceModel;
    @Resource
    private WorkOrderModel workOrderModel;
    @Resource
    private ProductModel productModel;

    @Resource
    private ClueModel clueModel;
    @Resource
    private MarketActivityModel marketActivityModel;
    @Resource
    private CostAdjustModel costAdjustModel;
    @Resource
    private RuleBusinessLogger ruleBusinessLogger;
    @Resource
    private PackageHelp packageHelp;
    @Resource
    private IndexTypeModel indexTypeModel;
    @Resource
    private ScoreCalculateService scoreCalculateService;
    @Resource
    private WorkflowBackupDataModel workflowBackupDataModel;
    @Resource
    private WorkflowWorkOrderV2FeignClient workflowWorkOrderV2FeignClient;
    @Resource
    private FormDataHelp formDataHelp;

    @Override
    public String type() {
        return WorkflowNodeTypeEnum.UPDATE_NODE.getName();
    }

    @Override
    public void before(WorkflowTransferPOJO workflowTransferPOJO) {
        super.before(workflowTransferPOJO);
    }

    @Override
    public WorkflowProcessResultPojo process(WorkflowTransferPOJO workflowTransferPojo, WorkflowNodeEntity workflowNodeEntity, Long lastNodeId, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) {
        try {
            String corpid = workflowNodeEntity.getCorpid();
            Integer feeType = packageHelp.getFeeType(corpid);
            FlowDatas flowDatas = workflowTransferPojo.getFlowDatas() == null ? new FlowDatas() : workflowTransferPojo.getFlowDatas();
            Map<String, FlowData> nodeIdMap = Objects.isNull(flowDatas.getNodeIdMap()) ? new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY) : flowDatas.getNodeIdMap();
            FlowData empayFlowData = new FlowData(workflowNodeEntity.getFormId(), workflowNodeEntity.getAppId(), workflowNodeEntity.getMenuId(),
                    workflowNodeEntity.getSaasMark(), workflowNodeEntity.getBusinessType(), new ArrayList<>(), new ArrayList<>());
            nodeIdMap.put(workflowNodeEntity.getId().toString(), empayFlowData);
            flowDatas.setNodeIdMap(nodeIdMap);
            workflowTransferPojo.setFlowDatas(flowDatas);
            if (!Objects.equals(PackageTypeEnum.ULTIMATE.getType(), feeType)) {
                logger(workflowTransferPojo, workflowNodeEntity, WorkflowTaskLogStatusEnum.PASS, new WorkflowException(MessageConstant.WORKFLOW_NODE_VERSION_NOT_SUPPORT));
                return new WorkflowProcessResultPojo(true, false);
            }
             UpdateRecordNode updateRecordNode = JSON.parseObject(workflowNodeEntity.getConfigData(), UpdateRecordNode.class);
            List<Long> updateIdList = new ArrayList<>();
            if (Objects.nonNull(updateRecordNode) && CollectionsUtil.isNotEmpty(updateRecordNode.getOperations())) {

                List<? extends PaasFormSubDataEntity> targetSubDataList = new ArrayList<>();
                Map<Long, List<Long>> workflowNodeDataIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                // 以工作流节点id为key的数据容器
                Map<Long, PaasFormDataEntityExt> workflowFormDataMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                Map<Long, JSONObject> dataMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                WorkflowNodeEntity targetNode = workflowNodeModel.getByKey(updateRecordNode.getWorkflowNodeId(), corpid);
                if (Objects.isNull(targetNode)) {
                    logger(workflowTransferPojo, workflowNodeEntity, WorkflowTaskLogStatusEnum.FAIL, new WorkflowException(MessageConstant.WORKFLOW_NODE_FAIL_NO_TARGET));
                    return new WorkflowProcessResultPojo(false, false);
                }
                PaasFormDataEntityExt paasFormDataEntity = WorkflowUtil.getFormData(workflowTransferPojo);
                Data data = workflowTransferPojo.getData();
                workflowFormDataMap.put(data.getNodeId(), paasFormDataEntity);
                dataMap.put(data.getNodeId(), paasFormDataEntity.getData());
                if (Objects.equals(0, updateRecordNode.getEditedData()) && WorkflowOperateEnum.updateOperateList().contains(workflowTransferPojo.getOperate())) {
                    // 触发表单的数据来源是编辑前还是编辑后
                    paasFormDataEntity = WorkflowUtil.setData(workflowTransferPojo.getOldData().getId(), corpid, workflowTransferPojo.getOldData());
                    workflowFormDataMap.put(data.getNodeId(), paasFormDataEntity);
                    dataMap.put(data.getNodeId(), paasFormDataEntity.getData());
                } else if (Objects.equals(2, updateRecordNode.getEditedData()) && WorkflowOperateEnum.updateOperateList().contains(workflowTransferPojo.getOperate())) {
                    // 触发事件编辑前数据
                    if (Objects.equals(workflowTransferPojo.getOperate(), WorkflowOperateEnum.UPDATE_BATCH.getType())) {
                        Data oldData = workflowTransferPojo.getOldData();
                        paasFormDataEntity = WorkflowUtil.setData(oldData.getId(), corpid, oldData.getData(), oldData.getFormId(), oldData.getSaasMark(), oldData.getBusinessType());
                    } else {
                        WorkflowBackupDataEntity workflowBackupDataEntity = workflowBackupDataModel.getByKey(workflowTransferPojo.getBackupDataId(), corpid);
                        paasFormDataEntity = WorkflowUtil.setData(workflowBackupDataEntity.getDataId(), corpid, workflowBackupDataEntity.getData(), data.getFormId(), data.getSaasMark(), data.getBusinessType());
                    }
                    workflowFormDataMap.put(data.getNodeId(), paasFormDataEntity);
                    dataMap.put(data.getNodeId(), paasFormDataEntity.getData());
                }


                if (!Objects.equals(BasicConstant.ONE, updateRecordNode.getTriggerNodeFlag())) {
                    FlowData flowData = nodeIdMap.get(updateRecordNode.getWorkflowNodeId().toString());
                    List<Long> targetSubIdList = flowData.getSubDataIdIn();
                    List<Long> targetIdList = flowData.getIds();
                    if (targetIdList.size() > PaasConstant.LIMIT_MAX_NUM) {
                        // 如果数据超过了限制了，不在执行下方逻辑
                        FlowData updateNodeFlowData = new FlowData(workflowNodeEntity.getFormId(), workflowNodeEntity.getAppId(), workflowNodeEntity.getMenuId(), workflowNodeEntity.getSaasMark(), workflowNodeEntity.getBusinessType(),
                                new ArrayList<>(), null);
                        nodeIdMap.put(workflowNodeEntity.getId().toString(), updateNodeFlowData);
                        flowDatas.setNodeIdMap(nodeIdMap);
                        workflowTransferPojo.setFlowDatas(flowDatas);
                        logger(workflowTransferPojo, workflowNodeEntity, WorkflowTaskLogStatusEnum.PASS, new WorkflowException(MessageConstant.WORKFLOW_NODE_PASS_UPDATE_DATA, 0));
                        return new WorkflowProcessResultPojo(true, false);
                    }

                    if (CollectionsUtil.isNotEmpty(targetSubIdList)) {
                        IndexTypeEnum indexTypeEnum = indexTypeModel.getSubIndexType(corpid, flowData.getBusinessType(), flowData.getSaasMark());
//                        TODO 需要改成es调用
                        targetSubDataList = paasFormSubDataModel.getByIdList(targetSubIdList, corpid, indexTypeEnum);
                    }
                    workflowNodeDataIdMap.put(updateRecordNode.getWorkflowNodeId(), targetIdList);
                }
                List<FilterCondition> conditions = new ArrayList<>();
                if (Objects.equals(WorkflowNodeTypeEnum.MULTI_DATA_NODE.getType(), targetNode.getType())) {
                    ObtainMultiDataNode obtainMultiDataNode = JSON.parseObject(targetNode.getConfigData(), ObtainMultiDataNode.class);
                    if (Objects.nonNull(obtainMultiDataNode)) {
                        conditions = obtainMultiDataNode.getFilterCondition();
                    }
                } else if (Objects.equals(WorkflowNodeTypeEnum.SINGLE_DATA_NODE.getType(), targetNode.getType())) {
                    ObtainSingleDataNode obtainSingleDataNode = JSON.parseObject(targetNode.getConfigData(), ObtainSingleDataNode.class);
                    if (Objects.nonNull(obtainSingleDataNode)) {
                        conditions = obtainSingleDataNode.getFilterCondition();
                    }
                }

                List<WorkflowOperationsPojo> subOperationList = new ArrayList<>();
                List<WorkflowOperationsPojo> mainOperationList = new ArrayList<>();
                updateRecordNode.getOperations().forEach(item->{
                    String targetAttr = item.getAttr();
                    List<String> targetAttrList = ExplainUtil.getAttrByPoint(targetAttr);
                    if (targetAttrList.size() == BasicConstant.TWO) {
                        subOperationList.add(item);
                    } else {
                        mainOperationList.add(item);
                    }
                });
                List<PaasFormDataEntityExt> targetDataList = new ArrayList<>();
                WorkflowFilterConditionPoJo workflowFilterConditionPoJo =  getSubFormCondition(conditions);
                if (!Objects.equals(BasicConstant.ONE, updateRecordNode.getTriggerNodeFlag())) {
                    // 触发表单是“获取多条数据”或者“获取单条数据”
                    for (Map.Entry<Long, List<Long>> entry : workflowNodeDataIdMap.entrySet()) {
                        Long k = entry.getKey();
                        FlowData flowData = nodeIdMap.get(k.toString());
                        targetDataList = formDataHelp.getByDataIdList(flowData.getIds(), flowData.getBusinessType(), flowData.getSaasMark(), flowData.getFormId(), corpid);
                    }
                } else {
                    // 触发表单是“触发节点”
                    Data triggerData = data;
                    targetDataList = formDataHelp.getByDataIdList(Collections.singletonList(triggerData.getId()), triggerData.getBusinessType(), triggerData.getSaasMark(), triggerData.getFormId(), corpid);
                }

                // 字段解释
                WorkflowDataPojo workflowDataPojo = workflowDataNodeHelp.updateNodeGetExplainMap(conditions, workflowNodeEntity, updateRecordNode.getOperations());
                // 子表单字段解释
                WorkflowExplainPojo workflowExplainPojo = WorkflowNodeUtil.getExplainMapByUpdateNode(updateRecordNode, data, conditions, workflowNodeEntity, workflowDataPojo);
                Map<String, PaasFormDataEntityExt> formDataMap = workflowDataNodeHelp.getLinkDataMap(paasFormDataEntity, corpid, workflowExplainPojo.getThisExplainMap());
                WorkflowRulePojo workflowRulePojo = new WorkflowRulePojo();
                workflowRulePojo.setFormDataMap(formDataMap);
                workflowExplainPojo.setSubOperationList(subOperationList);

                // 子表单和主表单的对应
                Map<Long, List<PaasFormSubDataEntity>> subFormDataMap = new HashMap<>(targetDataList.size());
                targetSubDataList.forEach(subData -> {
                    subFormDataMap.computeIfAbsent(subData.getDataId(), v -> new ArrayList<>()).add(subData);
                });

                Map<Long, PaasFormDataEntityExt> parentFormDataMap = new HashMap<>(targetDataList.size());
                targetDataList.forEach(item->{
                    parentFormDataMap.put(item.getDataId(), item);
                    if (subFormDataMap.isEmpty()) {
                        subFormDataMap.put(item.getDataId(), new ArrayList<>());
                    }
                });
                // 赋值给主字段（子表单外字段）
                List<UpdateDataEntity> updateDataList = setMainOperator( targetDataList,  updateRecordNode,  workflowFilterConditionPoJo,
                         dataMap,  workflowExplainPojo,  workflowNodeEntity,  workflowDataPojo,
                        workflowFormDataMap,  workflowTransferPojo, mainOperationList, subFormDataMap, workflowRulePojo);
                String parentAttr = "";
                if (CollectionsUtil.isNotEmpty(subOperationList)) {

                    List<UpdateSubDataEntity> updateSubDataList = subFieldOperator(subFormDataMap, subOperationList, workflowExplainPojo, parentFormDataMap, workflowFormDataMap,
                            dataMap, workflowDataPojo, workflowFilterConditionPoJo, workflowNodeEntity, workflowTransferPojo, updateRecordNode, workflowRulePojo);
                   // 将子表单放入主表中，主要是为了拼装数据
                    parentAttr = ExplainUtil.getAttrByPoint(subOperationList.get(0).getAttr()).get(0);
                   // 将子表单需要更新的数据放入主表数据中
                    DataTypeUtil.setSubDataList(updateDataList, updateSubDataList, parentAttr, corpid);
                }
                updateIdList = update(updateDataList, targetDataList, workflowExplainPojo.getTargetExplainMap(), workflowNodeEntity,  updateRecordNode.getOperations(), workflowTransferPojo);

                if (updateIdList.contains(data.getId()) && FormUtil.sameForm(data.getFormId(), workflowNodeEntity.getFormId(), data.getBusinessType(), workflowNodeEntity.getBusinessType())) {
                    // 当改到触发节点数据时，需要重新更新下上下文
                    JSONObject jsonObject = new JSONObject();
                    updateDataList.forEach(item->{
                        if (Objects.equals(item.getId(), data.getId())) {
                            item.getData().forEach(value->{
                                String key = value.getEsKey().replace( StringConstant.JSON_DATA + StringConstant.POINT, "");
                                jsonObject.put(key, value.getValue());
                            });
                        }
                    });
                    if (StringUtils.isNotEmpty(parentAttr)) {
                        IndexTypeEnum indexTypeEnum = indexTypeModel.getSubIndexType(corpid, workflowTransferPojo.getData().getBusinessType(), workflowTransferPojo.getData().getSaasMark());
                        List<? extends PaasFormSubDataEntity> list = paasFormSubDataModel.getListByIdAndAttr(workflowTransferPojo.getData().getId(), corpid, indexTypeEnum, parentAttr);
                        if (CollectionsUtil.isNotEmpty(list)) {
                            JSONArray jsonArray = new JSONArray();
                            list.forEach(item->{
                                JSONObject subData = new JSONObject();
                                subData.put(BusinessConstant.SUB_DATA_ID, item.getId());
                                subData.putAll(item.getData());
                                jsonArray.add(subData);
                            });
                            jsonObject.put(parentAttr, jsonArray);
                        }
                    }
                    data.getData().putAll(jsonObject);
                }
                logger(workflowTransferPojo, workflowNodeEntity, WorkflowTaskLogStatusEnum.PASS, new WorkflowException(MessageConstant.WORKFLOW_NODE_PASS_UPDATE_DATA, updateDataList.size()));
            }
            FlowData flowData = new FlowData(workflowNodeEntity.getFormId(), workflowNodeEntity.getAppId(), workflowNodeEntity.getMenuId(), workflowNodeEntity.getSaasMark(), workflowNodeEntity.getBusinessType(),
                    updateIdList, null);
            nodeIdMap.put(workflowNodeEntity.getId().toString(), flowData);
            flowDatas.setNodeIdMap(nodeIdMap);
            workflowTransferPojo.setFlowDatas(flowDatas);
            return new WorkflowProcessResultPojo(true, false);
        } catch (WorkflowException e) {
            logger(workflowTransferPojo, workflowNodeEntity, WorkflowTaskLogStatusEnum.FAIL, e);
            return new WorkflowProcessResultPojo(false, false);
        } catch (XbbException e) {
            WorkflowException workflowException = new WorkflowException(e.getMsg());
            logger(workflowTransferPojo, workflowNodeEntity, WorkflowTaskLogStatusEnum.FAIL, workflowException);
            LOGGER.error("WorkflowNodeUpdateStrategy.process error", e);
            return new WorkflowProcessResultPojo(false, false);
        } catch (Exception e) {
            LOGGER.error("WorkflowNodeUpdateStrategy.process error", e);
            WorkflowException workflowException = new WorkflowException(e.getMessage());
            logger(workflowTransferPojo, workflowNodeEntity, WorkflowTaskLogStatusEnum.FAIL, workflowException);
            return new WorkflowProcessResultPojo(false, false);
        }

    }

    private List<Long> update(List<UpdateDataEntity> updateList, List<PaasFormDataEntityExt> formDataList, Map<String, FieldAttrEntity> targetExplain,
                        WorkflowNodeEntity workflowNodeEntity, List<WorkflowOperationsPojo> operations, WorkflowTransferPOJO workflowTransferPOJO) throws XbbException {
        List<Long> updateIdList = new ArrayList<>();
        if (CollectionsUtil.isEmpty(updateList)) {
            return updateIdList;
        }
        String corpid = workflowNodeEntity.getCorpid();
        // 判断字段是否可编辑暂时不要
        if(Objects.nonNull(operations) && CollectionsUtil.isNotEmpty(updateList)){
            updateIdList = updateList.stream().map(item -> item.getId()).collect(Collectors.toList());
            if (Objects.equals(SaasMarkEnum.PAAS.getCode(), workflowNodeEntity.getSaasMark())) {
                paasFormDataModel.updateBatch(updateList, corpid, WriteRequest.RefreshPolicy.WAIT_UNTIL);
            } else {
                XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(workflowNodeEntity.getBusinessType());
                switch (xbbRefTypeEnum) {
                    case CUSTOMER_MANAGEMENT:
                        // 客户
                        customerModel.updateBatch(updateList, corpid, WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        //评分更新(业务规则修改客户信息 只编辑)
                        DataScoreUpdateBatchDTO dataScoreUpdateBatchDTO = new DataScoreUpdateBatchDTO();
                        dataScoreUpdateBatchDTO.setCorpid(corpid);
                        dataScoreUpdateBatchDTO.setUserId(workflowTransferPOJO.getUser().getUserId());
                        dataScoreUpdateBatchDTO.setBusinessType(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
                        dataScoreUpdateBatchDTO.setUpdateIdList(updateIdList);
                        dataScoreUpdateBatchDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
                        scoreCalculateService.updateBatch(dataScoreUpdateBatchDTO);
                        break;
                    case CONTACT:
                        // 联系人
                        contactModel.updateBatch(updateList, corpid, WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        break;
                    case CUSTOMER_COMMUNICATE:
                        // 跟进记录
                        customerCommunicateModel.updateBatch(updateList, corpid, WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        break;
                    case COMMUNICATE_PLAN:
                        // 访客计划
                        communicatePlanModel.updateBatch(updateList, corpid, WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        break;
                    case SALES_OPPORTUNITY:
                        // 机会
                        opportunityModel.updateBatch(updateList, corpid, WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        break;
                    case CONTRACT:
                        //合同订单
                        contractModel.updateBatch(updateList, corpid, WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        break;
                    case REFUND:
                        // 退货退款
                        refundModel.updateBatch(updateList, corpid, WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        break;
                    case PRODUCT:
                        // 产品
                        productModel.updateBatch(updateList, corpid, WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        break;
                    case QUOTATION:
                        // 报价单
                        quotationModel.updateBatch(updateList, corpid, WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        break;
                    case PURCHASE:
                        // 采购合同
                        purchaseModel.updateBatch(updateList, corpid, WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        break;
                    case SUPPLIER:
                        // 供应商
                        supplierModel.updateBatch(updateList, corpid, WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        break;
                    case SUPPLIER_COMMUNICATE:
                        // 供应商跟进记录
                        supplierCommunicateModel.updateBatch(updateList, corpid, WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        break;
                    case SUPPLIER_CONTACT:
                        // 供应商联系人
                        supplierContactModel.updateBatch(updateList, corpid, WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        break;
                    case RETURNED_PURCHASE:
                        // 采购退货单
                        returnedPurchaseModel.updateBatch(updateList, corpid, WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        break;
                    case BOM_BILL:
                        // bom单
                        bomBillModel.updateBatch(updateList, corpid, WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        break;
                    case PRODUCTION_ORDER:
                        // 生产单
                        productionOrderModel.updateBatch(updateList, corpid, WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        break;
                    case ASSEMBLE:
                        // 装配出入单
                        assembleModel.updateBatch(updateList, corpid, WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        break;
                    case INSTOCK:
                    case PURCHASE_INSTOCK:
                    case OTHER_INSTOCK:
                    case REFUND_INSTOCK:
                    case RETURNED_MATERIEL_INSTOCK:
                    case PRODUCTION_INSTOCK:
                        // 入库单
                        instockModel.updateBatch(updateList, corpid, WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        break;
                    case OUTSTOCK:
                    case CONTRACT_OUTSTOCK:
                    case OTHER_OUTSTOCK:
                    case RETURNED_PURCHASE_OUTSTOCK:
                    case PRODUCTION_MATERIEL_OUTSTOCK:
                        // 出库单
                        outstockModel.updateBatch(updateList, corpid, WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        break;
                    case INVENTORY:
                        // 盘点单
                        inventoryModel.updateBatch(updateList, corpid, WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        break;
                    case TRANSFER:
                        // 调拨单
                        transferModel.updateBatch(updateList, corpid, WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        break;
                    case WAREHOUSE:
                        // 仓库
                        warehouseModel.updateBatch(updateList, corpid, WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        break;
                    case WORK_ORDER:
                        // 工单
                        workOrderModel.updateBatch(updateList, corpid, WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        break;
                    case PAYMENT:
                        paymentModel.updateBatch(updateList, corpid, WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        break;
                    case PAYMENT_SHEET:
                        paymentSheetModel.updateBatch(updateList, corpid, WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        break;
                    case PAY_PLAN:
                        payPlanModel.updateBatch(updateList, corpid, WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        break;
                    case PAY_SHEET:
                        payPlanSheetModel.updateBatch(updateList, corpid, WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        break;
                    case INVOICE:
                        invoiceModel.updateBatch(updateList, corpid, WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        break;
                    case PURCHASE_INVOICE:
                        purchaseInvoiceModel.updateBatch(updateList, corpid,  WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        break;
                    case CLUE:
                        clueModel.updateBatch(updateList, corpid,  WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        // 更新评分(业务规则 只编辑)
                        dataScoreUpdateBatchDTO = new DataScoreUpdateBatchDTO();
                        dataScoreUpdateBatchDTO.setCorpid(corpid);
                        dataScoreUpdateBatchDTO.setUserId(workflowTransferPOJO.getUser().getUserId());
                        dataScoreUpdateBatchDTO.setBusinessType(XbbRefTypeEnum.CLUE.getCode());
                        dataScoreUpdateBatchDTO.setUpdateIdList(updateIdList);
                        dataScoreUpdateBatchDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
                        scoreCalculateService.updateBatch(dataScoreUpdateBatchDTO);
                        break;
                    case MARKET_ACTIVITY:
                        marketActivityModel.updateBatch(updateList, corpid,  WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        break;
                    case COST_ADJUST:
                        costAdjustModel.updateBatch(updateList, corpid,  WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        break;
                    case WORK_ORDER_V2:
                    case RECEIPT_ORDER:
                    case SERVICE_PROJECT:
                        WorkflowUpdateDataDTO workflowUpdateDataDTO = new WorkflowUpdateDataDTO(corpid, updateList, workflowNodeEntity.getBusinessType());
                        workflowWorkOrderV2FeignClient.updateData(workflowUpdateDataDTO, LocaleContextHolder.getLocale().toString());
                        break;
                    default:
                        break;
                }
            }
            try {
                RuleTargetPojo ruleTargetPojo = new RuleTargetPojo();
                ruleTargetPojo.setFormId(workflowNodeEntity.getFormId());
                ruleTargetPojo.setLinkBusinessType(workflowNodeEntity.getBusinessType());
                ruleTargetPojo.setLinkSaasMark(workflowNodeEntity.getSaasMark());
                RuleBusinessLogDTO businessLogDTO = new RuleBusinessLogDTO(corpid, ruleTargetPojo, formDataList,
                        targetExplain);
                // 增加 i18n 参数
                Locale locale = LocaleContextHolder.getLocale();
                String lang = locale.toString();
                businessLogDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
                UserVO userVO = new UserVO();
                User user = workflowTransferPOJO.getUser();
                userVO.setUserId(user.getUserId());
                userVO.setName(user.getName());
                businessLogDTO.setLoginUserName(user.getName());
                businessLogDTO.setUserId(user.getUserId());
                businessLogDTO.setLoginUser(userVO);
                businessLogDTO.setCorpid(workflowTransferPOJO.getCorpid());
                businessLogDTO.setValueList(updateList);
                businessLogDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
                ruleBusinessLogger.writeLog(businessLogDTO, updateList);
            } catch (Exception e) {
                LOGGER.error("WorkflowNodeUpdateStrategy.update error；", e);
            }
        }
        return updateIdList;
    }



    /**
     * 给子表单外的字段赋值
     * @param targetDataList
     * @param updateRecordNode
     * @param workflowFilterConditionPoJo
     * @param dataMap
     * @param workflowExplainPojo
     * @param workflowNodeEntity
     * @param workflowDataPojo
     * @param workflowFormDataMap
     * @param workflowTransferPojo
     * @param mainOperationList
     * @return
     * @throws XbbException
     */
    private List<UpdateDataEntity> setMainOperator(List<PaasFormDataEntityExt> targetDataList, UpdateRecordNode updateRecordNode, WorkflowFilterConditionPoJo workflowFilterConditionPoJo,
                                 Map<Long, JSONObject> dataMap, WorkflowExplainPojo workflowExplainPojo, WorkflowNodeEntity workflowNodeEntity, WorkflowDataPojo workflowDataPojo,
                                 Map<Long, PaasFormDataEntityExt> workflowFormDataMap, WorkflowTransferPOJO workflowTransferPojo, List<WorkflowOperationsPojo> mainOperationList,
                                                   Map<Long, List<PaasFormSubDataEntity>> subFormDataMap, WorkflowRulePojo workflowRulePojo) throws XbbException {
        List<UpdateDataEntity> updateDataList = new ArrayList<>();
        if (CollectionUtils.isEmpty(mainOperationList)) {
            return new ArrayList<>();
        }
        if (CollectionUtils.isEmpty(targetDataList)) {
            return new ArrayList<>();
        }
        long now = DateTimeUtil.getInt();
        Map<String, Map<String, FieldAttrEntity>> thisExplainMap = workflowExplainPojo.getThisExplainMap();
        // 获取子表单的数据
        JSONArray thisSubDataArray = new JSONArray();
        boolean isSubForm = workflowFilterConditionPoJo.getIsMainAndSubForm() || workflowFilterConditionPoJo.getIsSubFormAndMain() || workflowFilterConditionPoJo.getIsSubFormAndSubForm();
        if (isSubForm) {
            // 通过workflowFormDataMap获取数据，可拿到编辑前或者编辑后的数据
           thisSubDataArray = workflowFormDataMap.get(workflowFilterConditionPoJo.getHasSubFormNodeId()).getData().getJSONArray(workflowFilterConditionPoJo.getParentAttr());
        }
        for (PaasFormDataEntityExt formData : targetDataList) {
            if (Objects.equals(updateRecordNode.getTriggerNodeFlag(), BasicConstant.ZERO)) {
                workflowFormDataMap.put(updateRecordNode.getWorkflowNodeId(), formData);
                dataMap.put(updateRecordNode.getWorkflowNodeId(), formData.getData());
            }
            UpdateDataEntity updateDataEntity = new UpdateDataEntity();
            List<UpdateDataValueEntity> data = new ArrayList<>();
            updateDataEntity.setId(formData.getDataId());
            updateDataEntity.setCorpid(formData.getCorpid());
            updateDataEntity.setFormId(formData.getFormId());
            updateDataEntity.setUpdateTime(now);
            if (workflowFilterConditionPoJo.getIsMainAndSubForm() && Objects.nonNull(thisSubDataArray)) {
                // 条件为：目标表单表单主字段等于当前子表单内字段
                // 子表单字段赋值给目标表单主字段，需要拿到对应的子表单的数据
                List<JSONObject> updateSubDataList = new ArrayList<>();
                for (int i = 0; i < thisSubDataArray.size(); i++) {
                    JSONObject subDataJson = thisSubDataArray.getJSONObject(i);
                    boolean update = validateData(workflowFilterConditionPoJo, workflowExplainPojo, formData, workflowFormDataMap, workflowNodeEntity, subDataJson, formData.getData(), workflowRulePojo);
                    if (update) {
                        updateSubDataList.add(subDataJson);
                    }
                }
                if (CollectionsUtil.isNotEmpty(updateSubDataList)) {
                    dataMap.put(workflowFilterConditionPoJo.getHasSubFormNodeId(), updateSubDataList.get(updateSubDataList.size()-1));
                }
            } else if (workflowFilterConditionPoJo.getIsSubFormAndSubForm() && Objects.nonNull(thisSubDataArray)) {
                // 条件为：目标表单表单子字段等于当前子表单内字段
                // 子表单字段赋值给目标表单子字段，需要拿到对应的子表单的数据
                List<JSONObject> updateSubDataList = new ArrayList<>();
                for (int i = 0; i < thisSubDataArray.size(); i++) {
                    JSONObject subDataJson = thisSubDataArray.getJSONObject(i);
                    List<PaasFormSubDataEntity> list = subFormDataMap.get(formData.getDataId());
                    if (CollectionUtils.isNotEmpty(list)) {
                        for (PaasFormSubDataEntity paasFormSubDataEntity : list) {
                            if (validateData(workflowFilterConditionPoJo, workflowExplainPojo, formData, workflowFormDataMap, workflowNodeEntity, subDataJson, paasFormSubDataEntity.getData(), workflowRulePojo)) {
                                updateSubDataList.add(subDataJson);
                            }
                        }
                    }
                }
                if (CollectionsUtil.isNotEmpty(updateSubDataList)) {
                    dataMap.put(workflowFilterConditionPoJo.getHasSubFormNodeId(), updateSubDataList.get(updateSubDataList.size()-1));
                }
            }
            workflowDataPojo.setWorkflowNodeId(updateRecordNode.getWorkflowNodeId());
            Iterator<WorkflowOperationsPojo> operationsIterator = mainOperationList.iterator();
            while (operationsIterator.hasNext()) {
                WorkflowOperationsPojo item = operationsIterator.next();
                String targetAttr = item.getAttr();
                List<String> targetAttrList = ExplainUtil.getAttrByPoint(item.getAttr());
                if (targetAttrList.size() == BasicConstant.TWO) {
                    targetAttr = targetAttrList.get(0);
                }
                FieldAttrEntity targetField = workflowExplainPojo.getTargetExplainMap().get(targetAttr);
                if (Objects.isNull(targetField)) {
                    //  字段判断
                    throw new WorkflowException(BusinessRuleErrorCodeEnum.API_ERROR_261006.getMsg());
                }
                UpdateDataValueEntity updateDataValueEntity = new UpdateDataValueEntity();
                updateDataValueEntity.setKey(targetAttr);
                updateDataValueEntity.setEsKey(targetAttr);
                boolean thisIsSubForm = WorkflowNodeUtil.validateSubForm(item, thisExplainMap);
                if (thisIsSubForm) {
                    // 子字段赋值给主字段
                    // 子赋主
                    Object object = workflowOperatorMainSubFormService.getUpdateData(item, workflowExplainPojo, targetField, workflowFormDataMap, dataMap, workflowNodeEntity,
                            workflowDataPojo, workflowTransferPojo);
                    object = DataTypeUtil.setDataType(updateDataValueEntity, object, targetField.getFieldType());
                    updateDataValueEntity.setValue(object);
                } else {
                    // 主赋值主
                    Object object = workflowOperatorMainService.getUpdateData(item, workflowExplainPojo, targetField, workflowFormDataMap, dataMap, workflowNodeEntity,
                            workflowDataPojo, workflowTransferPojo);
                    object = DataTypeUtil.setDataType(updateDataValueEntity, object, targetField.getFieldType());
                    updateDataValueEntity.setValue(object);
                }
                data.add(updateDataValueEntity);
            }
            updateDataEntity.setData(data);
            updateDataList.add(updateDataEntity);
        }
        return updateDataList;
    }

    private boolean validateData(WorkflowFilterConditionPoJo workflowFilterConditionPoJo, WorkflowExplainPojo workflowExplainPojo, PaasFormDataEntityExt formData,
                                Map<Long, PaasFormDataEntityExt> workflowFormDataMap, WorkflowNodeEntity workflowNodeEntity, JSONObject subDataJson, JSONObject data, WorkflowRulePojo workflowRulePojo) throws XbbException {
        boolean update = false;
        for (FilterCondition item : workflowFilterConditionPoJo.getConditions()) {
            String targetAttr = item.getAttr();
            FieldAttrEntity targetField = workflowExplainPojo.getTargetExplainMap().get(targetAttr);
            if (Objects.isNull(targetField)) {
                //  字段判断
                throw new WorkflowException(BusinessRuleErrorCodeEnum.API_ERROR_261006.getMsg());
            }
            if (Objects.equals(WorkflowValueTypeEnum.DYNAMIC_VALUE.getType(), item.getValueType())) {
                // 这里只有动态值
                List<String> thisAttList = ExplainUtil.getAttrByPoint(item.getValueAttr());

                // 判断数据是否一致
                update = validateEqualsData(formData, workflowFormDataMap.get(workflowFilterConditionPoJo.getHasSubFormNodeId()), workflowExplainPojo, thisAttList,
                        targetField, workflowNodeEntity, item, data, subDataJson, workflowRulePojo);
                if (!update) {
                    break;
                }
            } else {
                // 判断数据是否一致
                update = validateEqualsData(formData, workflowFormDataMap.get(workflowFilterConditionPoJo.getHasSubFormNodeId()), workflowExplainPojo, new ArrayList<>(),
                        targetField, workflowNodeEntity, item, data, subDataJson, workflowRulePojo);
                if (!update) {
                    break;
                }
            }
        }
        return update;
    }

    /**
     * 子表单字段赋值
     * @param subFormDataMap
     * @param subOperationList
     * @param workflowExplainPojo
     * @param parentFormDataMap
     * @param workflowDataMap
     * @param dataMap
     * @param workflowDataPojo
     * @param workflowFilterConditionPoJo
     * @param workflowNodeEntity
     * @param workflowTransferPojo
     * @param updateRecordNode
     * @throws XbbException
     */
    private List<UpdateSubDataEntity>  subFieldOperator(Map<Long, List<PaasFormSubDataEntity>> subFormDataMap, List<WorkflowOperationsPojo> subOperationList, WorkflowExplainPojo workflowExplainPojo,
                                  Map<Long, PaasFormDataEntityExt> parentFormDataMap, Map<Long, PaasFormDataEntityExt> workflowDataMap, Map<Long, JSONObject> dataMap,
                                  WorkflowDataPojo workflowDataPojo, WorkflowFilterConditionPoJo workflowFilterConditionPoJo, WorkflowNodeEntity workflowNodeEntity,
                                  WorkflowTransferPOJO workflowTransferPojo, UpdateRecordNode updateRecordNode, WorkflowRulePojo workflowRulePojo) throws XbbException {
        try {
            List<UpdateSubDataEntity> updateSubDataList = new ArrayList<>();
            if (CollectionsUtil.isNotEmpty(subOperationList)) {

                Iterator<Map.Entry<Long, List<PaasFormSubDataEntity>>> subDataIterator = subFormDataMap.entrySet().iterator();
                Integer updateMethod = updateRecordNode.getUpdateMethod();
                while (subDataIterator.hasNext()) {
                    Map.Entry<Long, List<PaasFormSubDataEntity>> targetFormData = subDataIterator.next();

                    Long parentId = targetFormData.getKey();
                    PaasFormDataEntityExt parentFormData = parentFormDataMap.get(parentId);
                    if (Objects.isNull(parentFormData)) {
                        // 防止空指针问题
                        continue;
                    }
                    PaasFormDataEntityExt thisFormData = workflowDataMap.get(workflowFilterConditionPoJo.getHasSubFormNodeId());
                    JSONArray subDataArray = new JSONArray();
                    if (Objects.nonNull(thisFormData)) {
                        subDataArray = thisFormData.getData().getJSONArray(workflowFilterConditionPoJo.getParentAttr());
                    }
                    List<PaasFormSubDataEntity> subDataList = targetFormData.getValue();
                    if (workflowFilterConditionPoJo.getIsSubFormAndSubForm()) {
                        // 子表单字段赋值给子表单字段
                        if (Objects.nonNull(subDataArray)) {
                            for (int i = 0; i < subDataArray.size(); i++) {
                                JSONObject subDataJson = subDataArray.getJSONObject(i);
                                boolean update = false;
                                PaasFormSubDataEntity result = null;
                                for (PaasFormSubDataEntity subDataEntity : subDataList) {
                                    JSONObject data = subDataEntity.getData();
                                    for (FilterCondition item : workflowFilterConditionPoJo.getConditions()) {
                                        // 判断子表单的数据的条件是否匹配，查找出满足条件的数据
                                        List<String> thisAttList = ExplainUtil.getAttrByPoint(item.getValueAttr());
                                        String targetAttr = item.getAttr();
                                        List<String> targetAttList = ExplainUtil.getAttrByPoint(targetAttr);
                                        FieldAttrEntity targetField = WorkflowExplainUtil.getTargetSubField(workflowExplainPojo.getWorkOrderSubExplainMap(), workflowExplainPojo.getSubExplainMap(),
                                                workflowNodeEntity,targetAttList.get(0), targetAttList.get(1));
                                        // 判断数据是否一致
                                        update = validateEqualsData(parentFormData, thisFormData, workflowExplainPojo, thisAttList, targetField, workflowNodeEntity, item, data, subDataJson, workflowRulePojo);
                                        if (!update) {
                                            // 数据不一样，直接跳出循环
                                            break;
                                        }
                                    }
                                    if (update) {
                                        // 将条件满足的数据返回，将在下方进行计算或者赋值
                                        result = subDataEntity;
                                        break;
                                    }
                                }
                                UpdateSubDataEntity updateSubDataEntity = new UpdateSubDataEntity();
                                updateSubDataEntity.setParentId(parentId);
                                if (Objects.nonNull(result)) {
                                    updateSubDataEntity.setSubDataId(result.getId());
                                    dataMap.put(updateRecordNode.getWorkflowNodeId(), result.getData());
                                }
                                updateSubDataEntity.setFormId(parentFormData.getFormId());
                                if ( update && Objects.equals(BasicConstant.ONE, updateMethod)) {
                                    // 子表单更新子表单操作
                                    updateSubDataEntity.setSubDataId(result.getId());
                                    dataMap.put(workflowFilterConditionPoJo.getHasSubFormNodeId(), subDataJson);
                                    // 子表单字段赋值子表单字段
                                    List<UpdateDataValueEntity> list = setSubDataList(workflowFilterConditionPoJo, workflowNodeEntity, workflowExplainPojo,
                                            subOperationList, workflowDataPojo, workflowTransferPojo, workflowDataMap, dataMap);
                                    updateSubDataEntity.setSubDataList(list);
                                    updateSubDataList.add(updateSubDataEntity);
                                } else if (Objects.equals(BasicConstant.TWO, updateMethod)) {
                                    dataMap.put(workflowFilterConditionPoJo.getHasSubFormNodeId(), subDataJson);
                                    if (update) {
                                        dataMap.put(updateRecordNode.getWorkflowNodeId(), result.getData());
                                        // 子表单字段赋值子表单字段
                                        List<UpdateDataValueEntity>  list = setSubDataList(workflowFilterConditionPoJo, workflowNodeEntity, workflowExplainPojo,
                                                subOperationList, workflowDataPojo, workflowTransferPojo, workflowDataMap, dataMap);
                                        updateSubDataEntity.setSubDataList(list);
                                        updateSubDataList.add(updateSubDataEntity);
                                    } else {
                                        // 子表单插入子表单操作
                                        List<UpdateDataValueEntity> list = setSubDataList(workflowFilterConditionPoJo, workflowNodeEntity, workflowExplainPojo,
                                                subOperationList, workflowDataPojo, workflowTransferPojo, workflowDataMap, dataMap);
                                        updateSubDataEntity.setSubDataList(list);
                                        updateSubDataList.add(updateSubDataEntity);
                                        updateSubDataEntity.setSubDataId(null);

                                    }
                                }
                            }

                        }
                    } else if (workflowFilterConditionPoJo.getIsSubFormAndMain()) {
                        // 主字段赋值给子表单字段
                        for (PaasFormSubDataEntity subDataEntity : subDataList) {
                            JSONObject data = subDataEntity.getData();
                            UpdateSubDataEntity updateSubDataEntity = new UpdateSubDataEntity();
                            updateSubDataEntity.setParentId(parentId);
                            updateSubDataEntity.setSubDataId(subDataEntity.getId());
                            updateSubDataEntity.setFormId(parentFormData.getFormId());
                            dataMap.put(updateRecordNode.getWorkflowNodeId(), data);
                            workflowDataMap.put(updateRecordNode.getWorkflowNodeId(), parentFormData);
                            List<UpdateDataValueEntity> list = new ArrayList<>();
                            for (WorkflowOperationsPojo subOperation : subOperationList) {
                                String targetAttr = subOperation.getAttr();
                                List<String> targetAttrList = ExplainUtil.getAttrByPoint(targetAttr);
                                if (targetAttrList.size() == BasicConstant.TWO) {
                                    targetAttr = targetAttrList.get(0);
                                }
                                FieldAttrEntity targetField = workflowExplainPojo.getTargetExplainMap().get(targetAttr);
                                if (Objects.isNull(targetField)) {
                                    //  字段判断
                                    throw new WorkflowException(BusinessRuleErrorCodeEnum.API_ERROR_261006.getMsg());
                                }
                                UpdateDataValueEntity updateDataValueEntity = new UpdateDataValueEntity();
                                updateDataValueEntity.setKey(targetAttrList.get(1));
                                updateDataValueEntity.setEsKey(targetAttrList.get(1));

                                Object object = workflowOperatorSubFormMainService.getUpdateData(subOperation, workflowExplainPojo, targetField, workflowDataMap, dataMap, workflowNodeEntity,
                                        workflowDataPojo, workflowTransferPojo);
                                object = DataTypeUtil.setDataType(updateDataValueEntity, object, targetField.getFieldType());
                                updateDataValueEntity.setValue(object);
                                list.add(updateDataValueEntity);
                            }
                            updateSubDataEntity.setSubDataList(list);
                            updateSubDataList.add(updateSubDataEntity);
                        }

                    }
                }

            }
            return updateSubDataList;
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOGGER.error("WorkflowNodeUpdateStrategy.process error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    /**
     * 获取子表单给子表单赋值的字段
     * @param workflowFilterConditionPoJo
     * @param workflowNodeEntity 当前节点
     * @param workflowExplainPojo 字段容器
     * @param subOperationList 子表单字段list
     * @param workflowDataPojo
     * @param workflowTransferPojo 流转过程中的数据
     * @param workflowDataMap 数据容器，存有流水号等子表单外层数据
     * @param dataMap 数据容器，存有data中或者子表单中的数据
     * @return
     * @throws XbbException
     */
    private List<UpdateDataValueEntity> setSubDataList(WorkflowFilterConditionPoJo workflowFilterConditionPoJo, WorkflowNodeEntity workflowNodeEntity, WorkflowExplainPojo workflowExplainPojo,
                                 List<WorkflowOperationsPojo> subOperationList, WorkflowDataPojo workflowDataPojo, WorkflowTransferPOJO workflowTransferPojo,
                                Map<Long, PaasFormDataEntityExt> workflowDataMap, Map<Long, JSONObject> dataMap) throws XbbException {
        List<UpdateDataValueEntity> list = new ArrayList<>();
        // 子表单字段赋值子表单字段
        for (WorkflowOperationsPojo subOperation : subOperationList) {
            String targetAttr = subOperation.getAttr();
            List<String> targetAttrList = ExplainUtil.getAttrByPoint(targetAttr);

            FieldAttrEntity targetField = WorkflowExplainUtil.getTargetSubField(workflowExplainPojo.getWorkOrderSubExplainMap(), workflowExplainPojo.getSubExplainMap(),
                    workflowNodeEntity,targetAttrList.get(0), targetAttrList.get(1));
            UpdateDataValueEntity updateDataValueEntity = new UpdateDataValueEntity();
            updateDataValueEntity.setEsKey(targetAttrList.get(1));
            updateDataValueEntity.setKey(targetAttrList.get(1));
            Object object = workflowOperatorSubFormService.getUpdateData(subOperation, workflowExplainPojo, targetField, workflowDataMap, dataMap, workflowNodeEntity,
                    workflowDataPojo, workflowTransferPojo);
            // 获取值的类型，主要是给mysql判断是jsonObject还是jsonArray或者其他
            object = DataTypeUtil.setDataType(updateDataValueEntity, object, targetField.getFieldType());
            updateDataValueEntity.setValue(object);
            list.add(updateDataValueEntity);
        }
        return list;
    }

    /**
     * 判断两边的数据是否一致
     * @param workflowExplainPojo
     * @param thisAttrList
     * @param targetField
     * @param workflowNodeEntity
     * @param item
     * @param data
     * @param subDataJson
     * @return true 数据一致；false：数据不一致
     * @throws XbbException
     */
    private boolean validateEqualsData(PaasFormDataEntityExt targetFormData, PaasFormDataEntityExt triggerFormData, WorkflowExplainPojo workflowExplainPojo, List<String> thisAttrList, FieldAttrEntity targetField, WorkflowNodeEntity workflowNodeEntity,
                                 FilterCondition item, JSONObject data, JSONObject subDataJson, WorkflowRulePojo workflowRulePojo) throws XbbException {
        if (Objects.equals(WorkflowValueTypeEnum.DYNAMIC_VALUE.getType(), item.getValueType())) {
            // 动态值比对
            FieldAttrEntity fieldAttrEntity = WorkflowExplainUtil.getThisSubField( workflowExplainPojo.getWorkOrderSubExplainMap(), workflowExplainPojo.getSubExplainMap(),
                    item.getTargetFormId(), item.getTargetBusinessType(), item.getValueType(),thisAttrList.get(0), thisAttrList.get(1));
            WorkflowConditionFieldService conditionFieldHandler = workflowConditionFieldMap.get(targetField.getFieldType());
            Object target = conditionFieldHandler.handlerThisFormField(targetFormData, data, targetField, fieldAttrEntity,  workflowNodeEntity, item, workflowRulePojo);
            // 数据源的表单
            WorkflowConditionFieldService thisConditionFieldHandler = workflowConditionFieldMap.get(fieldAttrEntity.getFieldType());
            Object thisValue = thisConditionFieldHandler.handlerThisFormField(triggerFormData, subDataJson, fieldAttrEntity,  targetField,  workflowNodeEntity, item, workflowRulePojo);
            return ConditionUtil.equals(target, thisValue, item.getSymbol(), targetField.getFieldType(), fieldAttrEntity.getFieldType());
        } else {
            // 固定值比对
            WorkflowConditionFieldService conditionFieldHandler = workflowConditionFieldMap.get(targetField.getFieldType());
            Object target = conditionFieldHandler.handlerThisFormField(targetFormData, data, targetField, targetField,  workflowNodeEntity, item, workflowRulePojo);
            Object thisValue = conditionFieldHandler.handlerFixedValue(targetField, workflowNodeEntity, item);
            return ConditionUtil.equals(target, thisValue, item.getSymbol(), targetField.getFieldType(), targetField.getFieldType());
        }
    }

    /**
     * 根据条件，获取子表单相关信息
     * @param conditions
     * @return
     */
    private WorkflowFilterConditionPoJo getSubFormCondition(List<FilterCondition> conditions) {
        WorkflowFilterConditionPoJo workflowFilterConditionPoJo = new WorkflowFilterConditionPoJo();
        List<FilterCondition> copyConditionList = new ArrayList<>();
        // 子表单的节点
        Long hasSubFormNodeId = null;
        // 子表单的字段标识
        String parentAttr = null;
        Boolean isSubFormAndSubForm= false;
        Boolean isSubFormAndMain = false;
        Boolean isMainAndSubForm = false;
        for (FilterCondition item : conditions) {
            if (!Objects.equals(WorkflowValueTypeEnum.DYNAMIC_VALUE.getType(), item.getValueType())) {
                continue;
            }
            List<String> thisAttrList = ExplainUtil.getAttrByPoint(item.getValueAttr());
            if (thisAttrList.size() == BasicConstant.TWO) {
                parentAttr = thisAttrList.get(0);
            }
            if (item.getAttr().contains(FieldTypeEnum.SUB_FORM.getEsalias()) && item.getValueAttr().contains(FieldTypeEnum.SUB_FORM.getEsalias())) {
                hasSubFormNodeId = item.getTargetWorkflowNodeId();
                copyConditionList.add(item);
                isSubFormAndSubForm = true;
            }else if (item.getValueAttr().contains(FieldTypeEnum.SUB_FORM.getEsalias()) && !item.getAttr().contains(FieldTypeEnum.SUB_FORM.getEsalias())) {
                isMainAndSubForm = true;
                copyConditionList.add(item);
                hasSubFormNodeId = item.getTargetWorkflowNodeId();
            } else if (item.getAttr().contains(FieldTypeEnum.SUB_FORM.getEsalias()) && !item.getValueAttr().contains(FieldTypeEnum.SUB_FORM.getEsalias())) {
                hasSubFormNodeId = item.getTargetWorkflowNodeId();
                copyConditionList.add(item);
                isSubFormAndMain = true;
            }
        }
        workflowFilterConditionPoJo.setConditions(copyConditionList);
        workflowFilterConditionPoJo.setHasSubFormNodeId(hasSubFormNodeId);
        workflowFilterConditionPoJo.setParentAttr(parentAttr);
        workflowFilterConditionPoJo.setIsSubFormAndSubForm(isSubFormAndSubForm);
        workflowFilterConditionPoJo.setIsSubFormAndMain(isSubFormAndMain);
        workflowFilterConditionPoJo.setIsMainAndSubForm(isMainAndSubForm);

        return workflowFilterConditionPoJo;
    }

    @Override
    public void after(WorkflowTransferPOJO workflowTransferPOJO, WorkflowNodeEntity workflowNodeEntity) {
        super.after(workflowTransferPOJO, workflowNodeEntity);
    }

    @Override
    public void check() {
        super.check();
    }


    @Override
    public void logger(WorkflowTransferPOJO workflowTransferPOJO, WorkflowNodeEntity nodeEntity, WorkflowTaskLogStatusEnum workflowTaskLogStatusEnum, WorkflowException workflowException) {
        super.logger(workflowTransferPOJO, nodeEntity, workflowTaskLogStatusEnum, workflowException);
    }
}
